import axios from "axios";
import store from "@/store";
import {getToken} from "@/utils/auth";
import fileDownload from "js-file-download";

const  servisedown =axios.create({
  responseType:'arraybuffer'
})

servisedown.interceptors.request.use( config=>{

  if (store.getters.token) {

    config.headers['X-Token'] = getToken()
  }
   return config
},error => {
  console.error(error)
})


servisedown.interceptors.response.use(Response =>{
  const headers =Response.headers
  let reg =RegExp('/appliction\/json')
  if (headers['context-type'].match(reg)){
      Response.data =unitToString(Response.data)
  }else {
    let fileDownload =require('js-file-download')
    let fileName =headers['context-disposition'].split(';')[1].split('filename')[1];
    let contentType =headers['content-type'];
    fileName =decodeURIComponent(fileName);
    fileDownload(Response.data,fileName,contentType)

  }
}, error => {
  console.log(error)
})

function  unitToString(unitArray){
  let encodeString =String.fromCharCode.apply(null,new unitToString(unitArray))
  let decodeString =decodeURIComponent(escape(encodeString))
  return JSON.parse(decodeString)
}
export const downloadRequest = (url , params) =>{
  return servisedown({
    method:'get',
    url:`${url}`,
    data: params
  })
}

export default servisedown
